package com.zz.chenko.sys.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zz.chenko.common.enums.PageJumpModeEnum;
import com.zz.chenko.common.utils.EncryptUtil;
import com.zz.chenko.common.utils.UserUtil;
import com.zz.chenko.sys.dto.UserDto;
import com.zz.chenko.sys.entity.User;
import com.zz.chenko.sys.service.UserRoleService;
import com.zz.chenko.sys.service.UserService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Zhong
 * @since 2017-05-10
 */
@Controller
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    /**
     * 跳转到列表页
     *
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("sys/userList");
        return modelAndView;
    }

    /**
     * 跳转到表单页
     *
     * @param mode 页面跳转方式
     * @return
     */
    @RequestMapping("/form")
    public ModelAndView form(String mode) {
        ModelAndView modelAndView = new ModelAndView();
        if (PageJumpModeEnum.ADD.getKey().equals(mode)) { // 跳转到用户添加页
            modelAndView.setViewName("sys/userForm");
        }
        return modelAndView;
    }

    /**
     * 通过用户名取得用户信息
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public ModelAndView getUser(@PathVariable String name) {
        System.out.println(name);
        ModelAndView modelAndView = new ModelAndView("sys/userList");
        return modelAndView;
    }

    /**
     * 验证用户名
     *
     * @param loginName 用户名
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/check/loginName", method = RequestMethod.GET)
    public String checkLoginName(String loginName) {
        EntityWrapper<User> wrapper = new EntityWrapper<User>();
        wrapper.addFilter("login_name = {0}", loginName);
        int i = userService.selectCount(wrapper);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("valid", i == 0);
        return JSON.toJSONString(map);
    }

    /**
     * 添加用户
     *
     * @param userDto
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ModelAndView putUser(UserDto userDto) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            // 密码加密
            userDto.setLoginPassword(this.getEncryptPassword(userDto.getLoginPassword()));
            // 创建人
            userDto.setCreateUser(UserUtil.getUser().getLoginName());
            // 创建时间
            userDto.setCreateTime(DateTime.now().toDate());
            // 保存用户信息
            userService.insert(userDto);

            // 取出刚存的用户信息
            EntityWrapper<User> wrapper = new EntityWrapper<>();
            wrapper.orderBy("ID", false);
            User user = userService.selectOne(wrapper);

            userRoleService.saveByUserIdAndRoleIdList(user.getId(), userDto.getRoleIdList());

            modelAndView.setViewName("sys/userList");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    @RequestMapping(value = "", method = RequestMethod.PUT)
    public void postUser(UserDto userDto) {
    }

    @RequestMapping(value = "/test")
    public ModelAndView test(User user) {
        // UserExample.Criteria criteria = example.createCriteria();
        // criteria.andLoginNameEqualTo(user.getLoginName());
        // criteria.andPasswordEqualTo(user.getPassword());
        // model.addAttribute("user", user);
        EntityWrapper<User> wrapper = new EntityWrapper<User>();
        wrapper.addFilter("login_name = 'kaka'").and("login_name = {0}", "kaka", "kaka")
                .orNew("login_name = {0}", "kaka");
        System.out.println(userService.selectCount(wrapper));
        return new ModelAndView("login");
    }

    /**
     * 取得加密密码
     *
     * @param password 明文密码
     * @return
     */
    private String getEncryptPassword(String password) {
        String salt = String.valueOf(new Random().nextInt(100000000));
        String encryptSalt = EncryptUtil.base64Encode(salt);
        String encryptPassword = EncryptUtil.getMD5Pwd(password, salt);
        return encryptSalt + encryptPassword;
    }
}
